package com.example.backend.controller;

import com.example.backend.entity.ProductListing;
import com.example.backend.service.BuyerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import com.example.backend.DTO.ProductDisplay;
import com.example.backend.DTO.listProduct;

@RestController
@RequestMapping("/api/buyer")
public class BuyerController {
    /**
    * 买家
    * 注册《，登录《，提交资质《，修改密码《，下单《、确认收货《，售后（退换货）
    **/
    final static int accountType = 3;
    
    @Autowired
    private BuyerService buyerService;

    //注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> credentials ) {
        String username= credentials.get("username");
        String passWordF= credentials.get("passWordF");
        String passwordS= credentials.get("passwordS");
        String qualificationContent= credentials.get("qualificationContent");
        Map<String, Object> resp = new HashMap<>();
        //判断密码是否为空
        if (username == null || passWordF == null || passwordS == null || qualificationContent == null){
            resp.put("message", "输入不能为空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        if (!passwordS.equals(passWordF)){
            resp.put("message", "密码不一致");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }


        String result = buyerService.register(username, passWordF, passwordS, qualificationContent, accountType);
        if("用户已存在".equals( result)){
            resp.put("message", "用户已存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        if ("注册成功".equals( result)) {
            resp.put("message", result);
            return ResponseEntity.ok(resp);
        }
        resp.put("message", "未知错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(resp);
    }

    //登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials, HttpServletResponse response) {
        String accountId = credentials.get("accountId");
        String password = credentials.get("password");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || password == null) {
            resp.put("message", "accountId and password are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        // 调用登录服务
        String result = buyerService.login(accountId, password, accountType);
        
        if ("登录成功".equals(result)) {
            // 登录成功，设置Cookie
            Cookie accountCookie = new Cookie("accountId", accountId);
            accountCookie.setMaxAge(24 * 60 * 60); // 24小时
            accountCookie.setPath("/");
            response.addCookie(accountCookie);
            
            // 返回成功信息
            resp.put("message", result);
            resp.put("accountId", accountId);
            return ResponseEntity.ok(resp);
        } else {
            // 登录失败
            resp.put("message", result);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }
    
    //提交资质
    @PostMapping("/postQualificationContent")
    public ResponseEntity<Map<String, Object>> postQualificationContent(@RequestBody Map<String, String> credentials) {
        String accountId = credentials.get("accountId");
        String qualificationContent = credentials.get("qualificationContent");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || qualificationContent == null) {
            resp.put("message", "accountId and qualificationContent are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        // 调用提交资质服务
        String result = buyerService.postQualificationContent(accountId, qualificationContent, accountType);

        resp.put("message", result);
        if ("提交资质成功".equals(result)) {
            // 提交成功，返回成功信息
            return ResponseEntity.ok(resp);
        } else {
            // 提交失败
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }

    //修改密码
    @PostMapping("/changePassword")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> credentials) {
        String accountId = credentials.get("accountId");
        String oldPassword = credentials.get("oldPassword");
        String newPassword = credentials.get("newPassword");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || oldPassword == null || newPassword == null) {
            resp.put("message", "accountId, oldPassword and newPassword are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        // 调用修改密码服务
        String result = buyerService.changePassword(accountId, oldPassword, newPassword, accountType);

        resp.put("message", result);
        if ("修改密码成功".equals(result)) {
            // 修改成功，返回成功信息
            return ResponseEntity.ok(resp);
        } else {
            // 修改失败
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }

    //下单
    @PostMapping("/placeOrder")
    public ResponseEntity<Map<String, Object>> placeOrder(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        String result = buyerService.placeOrder(credentials);
        resp.put("message", result);
        if ("下单成功".equals(result)) {
            return ResponseEntity.ok(resp);
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
    }

    //获取已上架商品列表
    @GetMapping("/getAvailableProducts")
    public ResponseEntity<Map<String, Object>> getAvailableProducts() {
        Map<String, Object> resp = new HashMap<>();
        try {
            List<ProductListing> products = buyerService.getAvailableProducts();
            resp.put("message", "获取成功");
            resp.put("products", products);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "获取商品列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }

    //获取已下单的商品列表
    @PostMapping("/getPlacedProducts")
    public ResponseEntity<Map<String, Object>> getPlacedProducts(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        try {
            List<listProduct> products = buyerService.getPlacedProducts(credentials);
            resp.put("message", "获取成功");
            resp.put("products", products);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "获取商品列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }

    //退货
    @PostMapping("/returnProduct")
    public ResponseEntity<Map<String,String>> returnProduct(@RequestBody Map<String, String> credentials){
        Map<String, String> resp = new HashMap<>();
        try {
            String result = buyerService.returnProduct(credentials);
            resp.put("message", "退货成功");
            resp.put("result", result);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "退货失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }

    //确认收货
    @PostMapping("/confirmReceipt")
    public ResponseEntity<Map<String, Object>> confirmReceipt(@RequestBody Map<String, String> credentials){
        Map<String, Object> resp = new HashMap<>();
        try {
            //查询需要交易单号transaction_id，买家账号buyerId
            String transactionId = credentials.get("transactionId");
            String buyerId = credentials.get("buyerId");
            if (transactionId == null || buyerId == null){
                resp.put("message", "参数错误");
            }
            String result = buyerService.confirmReceipt(transactionId, buyerId);
            resp.put("message", result);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "确认收货失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }

    //确认付款
    @PostMapping("/pay")
    public ResponseEntity<Map<String, Object>> pay(@RequestBody Map<String, String> credentials){
        Map<String, Object> resp = new HashMap<>();
        try {
            //查询需要交易单号transaction_id，买家账号buyerId
            String transactionId = credentials.get("transactionId");
            String buyerId = credentials.get("buyerId");
            if (transactionId == null || buyerId == null){
                resp.put("message", "参数错误");
            }
            String result = buyerService.pay(transactionId, buyerId);
            resp.put("message", result);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "确认付款失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }
    //取消订单
    @PostMapping("/cancelOrder")
    public ResponseEntity<Map<String, Object>> cancelOrder(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String result = buyerService.cancelOrder(credentials);
            resp.put("message", result);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "取消订单失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }
}